#
# Copyright (c) 2023 supercell
#
# SPDX-License-Identifier: BSD-3-Clause
#

module Luce
  # A parser to parse a segment of source text.
  class TextParser
    getter source : String

    def initialize(@source : String)
    end

    # The current read position
    @position = 0

    def pos : Int32
      @position
    end

    # Whether the read position has reached the end of `source`.
    def done? : Bool
      @position == size
    end

    # The size of `source`.
    def size : Int32
      @source.size
    end

    # Walk the parser forward through any whitespace.
    #
    # Set *multiline* to `true` to support multiline, otherwise it will stop
    # before the line feed `Charcode::LF`.
    def move_through_whitespace(multiline : Bool = false) : Int32
      i = 0
      until done?
        char = char_at
        if char != Charcode::SPACE &&
           char != Charcode::TAB &&
           char != Charcode::VT &&
           char != Charcode::CR &&
           char != Charcode::FF &&
           !(multiline && char == Charcode::LF)
          return i
        end

        i += 1
        advance
      end
      i
    end

    def char_at(position : Int32? = nil) : Int32
      source.codepoint_at(position || @position)
    end

    # Moves the read position one character ahead.
    def advance : Nil
      advance_by 1
    end

    # Moves the read position for *length* characters. *length* can be negative.
    def advance_by(length : Int32) : Nil
      @position += length
    end

    # Returns a substring using a Range's *begin* and *end* as character indicies.
    def [](range : Range) : String
      @source[range]
    end
  end
end
